/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.ui;

import com.anhndt.audiobook.business.Resource;
import com.anhndt.audiobook.entity.ItemEntity;
import com.anhndt.audiobook.iface.ProcessListener;
import com.anhndt.audiobook.parser.ItemParser;
import com.anhndt.audiobook.ui.renderer.ItemRenderer;
import com.anhndt.audiobook.ui.renderer.ItemTickerRenderer;
import com.anhndt.audiobook.utils.DialogUtil;
import com.anhndt.audiobook.utils.StringUtil;
import com.anhndt.audiobook.utils.Util;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Display;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.FocusListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.list.DefaultListModel;
import com.sun.lwuit.list.ListCellRenderer;
import com.sun.lwuit.spinner.Spinner;
import java.util.Vector;

/**
 *
 * @author Sun
 */
public class ArticleForm extends BaseForm {

    private int counterItem;
    private int curPage;
    private int counterPage;
    protected int selectedIndex;
    private Spinner spinner;

    public ArticleForm(String title, BaseForm previous, ItemEntity parentEntity) {
        super(title, previous, parentEntity);
        setSupportSearch(true);
    }

    public ArticleForm(byte tag, String title, BaseForm previous, ItemEntity parentEntity) {
        super(tag, title, previous, parentEntity);
        setSupportSearch(true);
    }

    protected void releaseAll() {
        super.releaseAll();
        spinner = null;
    }

//    public void show() {
//        super.show();
//        if (listItem != null) {
//            listItem.getComponentForm().setFocused(listItem);
//        }
//    }

//    public boolean isSearch() {
//        return searching;
//    }
//
//    public void setSearch(boolean search) {
//        this.searching = search;
//    }
    private void calculatePage() {
        counterItem = parentEntity.counterChild;
        curPage = 1;
        counterPage = Math.max(Util.divRounded(counterItem, Util.displayCounter), 1);
    }

    protected String getTypeContentChild() {
        return "" + ItemEntity.TYPE_ARTICLE;
    }

    protected ListCellRenderer getRenderer() {
        return (Label.isDefaultTickerEnabled()) ? new ItemTickerRenderer(ItemRenderer.TYPE_RATE) : new ItemRenderer(ItemRenderer.TYPE_RATE);
    }

    protected void init() {
        //just setThirdSoftButton before create form;
        calculatePage();
        if (counterPage > 1 || getClass() == ArticlePartForm.class) {
            Display.getInstance().setThirdSoftButton(true);
        } else {
            Display.getInstance().setThirdSoftButton(false);
        }
        super.init();
        // Create container contain ListItem & PageNavigator
        final Vector articles = (parentEntity != null && parentEntity.size() > 0) ? parentEntity.getItemChildrends(getTypeContentChild()) : null;
        if (articles != null && articles.size() > 0) {
            changeListModel(articles, selectedIndex);
        }
        //create and add spinner
        if (counterPage > 1) {
            spinner = Spinner.create(1, counterPage + 1, 1, 1);
            spinner.addFocusListener(new FocusListener() {

                public void focusGained(Component cmp) {
                    Component c = spinner.getRenderer().getListCellRendererComponent(spinner, spinner.getSelectedItem(), spinner.getSelectedIndex(), true);
                    c.setFocusPainted(true);
                }

                public void focusLost(Component cmp) {
                    Component c = spinner.getRenderer().getListCellRendererComponent(spinner, spinner.getSelectedItem(), spinner.getSelectedIndex(), true);
                    c.setFocusPainted(false);
                }
            });
            spinner.setSelectCommandText(curPage + "/" + counterPage);
            listItem.setSelectCommandText(curPage + "/" + counterPage);
            spinner.addActionListener(this);
            spinner.addFocusListener(new FocusListener() {

                public void focusGained(Component cmp) {
                    //Do nothing
                }

                public void focusLost(Component cmp) {
                    spinner.setValue(new Integer(curPage));
                }
            });
//            Container con = new Container(new CenterLayout());
//            con.addComponent(spinner);
            body.addComponent(BorderLayout.SOUTH, spinner);
        }
        if (getClass() == ArticleForm.class && Util.displayThumb) {
            loadThumb(articles);
        }
    }

    protected void addCommand() {
        super.addCommand();
        //create Command Remove and Remove All
        if (tag == TAG_FAVORITE && parentEntity.size("" + ItemEntity.TYPE_ARTICLE) > 0) {
            Command cmdRemove = new Command(Resource.CMD_REMOVE);
            Command cmdRemoveAll = new Command(Resource.CMD_REMOVE_ALL);
            form.addCommand(cmdRemove);
            form.addCommand(cmdRemoveAll);
        }
        form.addCommand(cmdView);
    }
    protected ItemParser createParserGotoPage(ItemEntity entity, int page) {
        keySearch = (textSearch != null) ? textSearch.getText() : null;

        ItemParser p = null;
        if (tag != TAG_SEARCH) {
            //create parser normal
            p = new ItemParser(entity, null, "" + Util.displayCounter, "" + page, true);
        } else if (!StringUtil.isNullOrEmpty(keySearch)) {
            //create parser search
            p = new ItemParser(entity, keySearch, "" + Util.displayCounter, "" + page, true);
            p.checkLoaded = false;
        }
        return p;
    }

    protected boolean keyPressed(int keyCode) {
        if (form == null) {
            return super.keyPressed(keyCode);
        }
        Component focused = form.getFocused();
        //next page or prev page just apply if focus into listItem
        int keyGame = Display.getInstance().getGameAction(keyCode);
        int tmpCurPage = curPage;
        if (focused == listItem && keyGame == Display.GAME_RIGHT) {
            if (tmpCurPage < counterPage) {
                tmpCurPage++;
            } else {
                tmpCurPage = 1;
            }
            gotoPage(tmpCurPage);
            return false;
        } else if (focused == listItem && keyGame == Display.GAME_LEFT) {
            if (tmpCurPage == 1) {
                tmpCurPage = counterPage;
            } else {
                tmpCurPage--;
            }
            gotoPage(tmpCurPage);
            return false;
        }
        return super.keyPressed(keyCode);
    }

    protected void itemSelected() {
        if (listItem == null || listItem.size() == 0) {
            return;
        }
        listItem.setHandlesInput(true);
        selectedIndex = listItem.getSelectedIndex();
        final ItemEntity selectedItem = (ItemEntity) listItem.getSelectedItem();
        selectedItem.changeMarked(true);
        //create callback
        ProcessListener callback = new ProcessListener() {

            public void onSuccess(Object result, int index) {
                Vector articleParts = (Vector) selectedItem.getItemChildrends("" + ItemEntity.TYPE_ARTICLE_PART);
                //neu chi co 1 articlepart thi show man hinh MediaPlayer ngay
                int size = articleParts.size();
                if (size == 1) {
                    formChild = new MediaPlayerForm(title, ArticleForm.this, selectedItem, 0);
                } else if (size > 1) {
                    formChild = new ArticlePartForm(title, ArticleForm.this, selectedItem, selectedItem);
                }
                showFormChild(formChild);
            }

            public void onError(String status, int index) {
            }
        };
        //set lastIdArticle
        Util.lastArticleID = selectedItem.id;
        ItemParser parser = new ItemParser(selectedItem, null, "" + Util.displayCounter, "" + 1, true);
        getResponseItem(selectedItem, parser, callback);
    }

    private void gotoPage(final int page) {
        if (curPage == page) {
            return;
        }
        parentEntity.removeAllChilrends();
        ItemParser gotoPageParser = createParserGotoPage(parentEntity, page);
        if (gotoPageParser != null) {
            //create callback
            ProcessListener callback = new ProcessListener() {

                public void onSuccess(Object result, int index) {
                    curPage = page;
                    spinner.setValue(new Integer(curPage));
                    listItem.setSelectCommandText(curPage + "/" + counterPage);
                    spinner.setSelectCommandText(curPage + "/" + counterPage);
                    //neu load duoc item con
                    Vector items = parentEntity.getItemChildrends(getTypeContentChild());
                    changeListModel(items, 0);
                    //chi load thumb voi man hinh Article
                    if (getClass() == ArticleForm.class && Util.displayThumb) {
                        loadThumb(items);
                    }
                    form.show();
//                    ArticleForm.this.show();
                }

                public void onError(String status, int index) {
                }
            };
            getResponseItem(parentEntity, gotoPageParser, callback);
        }
    }

    public void actionPerformed(ActionEvent evt) {
        Command cmd = evt.getCommand();
        if (cmd == cmdBack) {
            backScreen();
        } else if (cmd == cmdView || evt.getSource() == listItem) {
            itemSelected();
        } else if (evt.getSource() == spinner) {
            try {
                int page = Integer.parseInt(spinner.getValue().toString());
                gotoPage(page);
            } catch (Exception e) {
            }
        } else if (cmd.getCommandName().equals(Resource.CMD_REMOVE) && form.getFocused() == listItem) {
            Command c = DialogUtil.showConfirmDialog(Resource.TXT_CONFIRM_DELETE);
            if (c != null && c.getCommandName().equals(Resource.CMD_OK)) {
                ItemEntity selectedEntity = (ItemEntity) listItem.getSelectedItem();
                ItemParser parserFavoriteDelete = new ItemParser(selectedEntity.id, ItemEntity.TYPE_FAVORITE_DELETE);
                parserFavoriteDelete.callservice();

                listItem.getModel().removeItem(listItem.getSelectedIndex());
                //remove from cache
                Vector favorites = parentEntity.getItemChildrends("" + ItemEntity.TYPE_ARTICLE);
                favorites.removeElement(selectedEntity);
            }
        } else if (cmd.getCommandName().equals(Resource.CMD_REMOVE_ALL)) {
            Command c = DialogUtil.showConfirmDialog(Resource.TXT_CONFIRM_DELETE_ALL);
            if (c != null && c.getCommandName().equals(Resource.CMD_OK)) {
                ItemParser parserFavoriteDeleteAll = new ItemParser(null, ItemEntity.TYPE_FAVORITE_DELETE_ALL);
                parserFavoriteDeleteAll.callservice();
                DefaultListModel d = (DefaultListModel) listItem.getModel();
                d.removeAll();
                form.revalidate();
                //remove from cache
                parentEntity.removeChild("" + ItemEntity.TYPE_ARTICLE);
            }
        }
    }

    protected void backScreen() {
        if (curPage != 1 || tag == TAG_SEARCH || AudioStore.getValueL10N("cache_article").equals("0")) {
            parentEntity.removeAllChilrends();
        }
        super.backScreen();
    }
}
